package com.hengtiansoft.lfy.chart.activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper.HXSyncListener;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.ContactListJson;
import com.hengtiansoft.lfy.chart.adapter.ContactAdapter;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.Friends;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.chart.db.InviteMessgeDao;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.domain.InviteMessage;
import com.hengtiansoft.lfy.chart.domain.InviteMessage.InviteMesageStatus;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.widget.Sidebar;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.hengtiansoft.pulltorefresh.PullToRefreshListView;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.HanziToPinyin;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

/**
 * 联系人列表页
 * 
 */
public class ContactlistActivity extends BaseActivity {
    public static final String TAG = "ContactlistFragment";
    private ContactAdapter adapter;
    private List<FriendsUser> contactList;
    private ListView listView;
    private PullToRefreshListView mPullListView;
    private boolean hasMoreData = true;
    private boolean hasData = true;
    private boolean isPullDownRefreshing;
    private boolean isPullUpRefreshing;
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private boolean hidden;
    private Sidebar sidebar;
    private InputMethodManager inputMethodManager;
    private List<String> blackList;
    ImageButton clearSearch;
    EditText query;
    HXContactSyncListener contactSyncListener;
    HXBlackListSyncListener blackListSyncListener;
    HXContactInfoSyncListener contactInfoSyncListener;
    View progressBar;
    Handler handler = new Handler();
    private FriendsUser toBeProcessUser;
    private String toBeProcessUsername;
    private static Context mContext;
    private MyGroupChangeListener groupChangeListener = null;
    private UserDao userDao;
    private InviteMessgeDao inviteMessgeDao;
    private ImageView mIvBack;
    private LinearLayout mLlHint;
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;

    class HXContactSyncListener implements HXSDKHelper.HXSyncListener {
        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "on contact list sync success:" + success);
            ContactlistActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (success) {
                                progressBar.setVisibility(View.GONE);
                                refresh();
                            } else {
                                String s1 = getResources().getString(
                                        R.string.get_failed_please_check);
                                Toast.makeText(mContext, s1, Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                            }
                        }

                    });
                }
            });
        }
    }

    class HXBlackListSyncListener implements HXSyncListener {

        @Override
        public void onSyncSucess(boolean success) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    blackList = EMClient.getInstance().contactManager().getBlackListUsernames();
                    refresh();
                }

            });
        }

    };

    class HXContactInfoSyncListener implements HXSDKHelper.HXSyncListener {

        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "on contactinfo list sync success:" + success);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressBar.setVisibility(View.GONE);
                    if (success) {
                        refresh();
                    }
                }
            });
        }

    }
    private boolean hideEnter = false;
    public static ContactlistActivity getActivity(){
        return (ContactlistActivity) mContext;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_contact_list);
        // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
        if (savedInstanceState != null
                && savedInstanceState.getBoolean("isConflict", false))
            return;
        inputMethodManager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        mPullListView = (PullToRefreshListView) findViewById(R.id.list);
        // 上拉，下拉
        mPullListView.setPullLoadEnabled(false);
        mPullListView.setScrollLoadEnabled(false);
        listView = mPullListView.getRefreshableView();
        listView.setDivider(null);

        sidebar = (Sidebar) findViewById(R.id.sidebar);
        sidebar.setListView(listView);

        // 黑名单列表
        blackList = EMClient.getInstance().contactManager().getBlackListUsernames();
        contactList = new ArrayList<FriendsUser>();
        // 获取设置contactlist
        getContactList();
        mLlHint = (LinearLayout) findViewById(R.id.ll_hint);
        // 搜索框
        query = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                adapter.getFilter().filter(s);
                if (s.length() > 0) {
                    mLlHint.setVisibility(View.GONE);
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    mLlHint.setVisibility(View.VISIBLE);
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });

        // 设置adapter
        adapter = new ContactAdapter(mContext, R.layout.row_contact,
                contactList);
        listView.setAdapter(adapter);
        mPullListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if (!CommonUtils.isNetWorkConnected(mContext)) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                    mPullListView.onPullDownRefreshComplete();
                    return;
                }
                isPullDownRefreshing = true;
                ContactListJson contactListJson = new ContactListJson(
                        Config.getUserName(),
                        Config.getUserToken());
                getContactListFromServer(Constants.FRIENDSLIST, contactListJson);
                setLastUpdateTime();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                mPullListView.onPullUpRefreshComplete();
            }
        });
        setLastUpdateTime();
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String username = adapter.getItem(position).getUsername();
                if (Constants.NEW_FRIENDS_USERNAME.equals(username)) {
                    // 进入申请与通知页面
                    FriendsUser user = ((DemoHXSDKHelper) HXSDKHelper
                            .getInstance()).getContactList()
                                    .get(Constants.NEW_FRIENDS_USERNAME);
                    user.setUnreadMsgCount(0);
                    startActivity(
                            new Intent(mContext, NewFriendsMsgActivity.class));
                } else if (Constants.GROUP_USERNAME.equals(username)) {
                    // 进入群聊列表页面
                    startActivity(new Intent(mContext, GroupsActivity.class));
                } else if (Constants.CHAT_ROOM.equals(username)) {
                    // 进入聊天室列表页面
                } else {
                    // demo中直接进入聊天页面，实际一般是进入用户详情页
                    // startActivity(new Intent(mContext, ChatActivity.class)
                    // .putExtra("userId", adapter.getItem(position)
                    // .getUsername()));
                    Intent intent = new Intent();
                    intent.setClass(mContext, PersonalDetailsActivity.class);
                    intent.putExtra("username",
                            adapter.getItem(position).getUsername());
                    intent.putExtra("type", "send");
                    mContext.startActivity(intent);
                }
            }
        });
        listView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 隐藏软键盘
                if (getWindow()
                        .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow(
                                getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

        ImageView addContactView = (ImageView) findViewById(
                R.id.iv_new_contact);
        // 进入添加好友页
        addContactView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(
                        new Intent(mContext, AddContactSearchActivity.class));
            }
        });
        registerForContextMenu(listView);

        progressBar = (View) findViewById(R.id.progress_bar);

        contactSyncListener = new HXContactSyncListener();
        HXSDKHelper.getInstance().addSyncContactListener(contactSyncListener);

        blackListSyncListener = new HXBlackListSyncListener();
        HXSDKHelper.getInstance()
                .addSyncBlackListListener(blackListSyncListener);

        contactInfoSyncListener = new HXContactInfoSyncListener();
        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager()
                .addSyncContactInfoListener(contactInfoSyncListener);

        if (!HXSDKHelper.getInstance().isContactsSyncedWithServer()) {
           // progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
        }
        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);
        init();
        initView();

        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = getWindow().getDecorView().getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight < 300) {
                    if(hideEnter) {
                        getWindow().getDecorView().requestFocus();
                        hideEnter=false;
                    }
                }else{

                    hideEnter=true;
                }
            }
        });
    }

    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        mPullListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }
        return mDateFormat.format(new Date(time));
    }

    // @Override
    // public void onActivityCreated(Bundle savedInstanceState) {
    // super.onActivityCreated(savedInstanceState);
    //
    // }

    private void initView() {

        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mIvBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (((AdapterContextMenuInfo) menuInfo).position > 1) {
            toBeProcessUser = adapter
                    .getItem(((AdapterContextMenuInfo) menuInfo).position);
            toBeProcessUsername = toBeProcessUser.getUsername();
            getMenuInflater().inflate(R.menu.context_contact_list, menu);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.delete_contact) {
            try {
                // 删除此联系人
                deleteContact(toBeProcessUser);
                // 删除相关的邀请消息
                InviteMessgeDao dao = new InviteMessgeDao(mContext);
                dao.deleteMessage(toBeProcessUser.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        return super.onContextItemSelected(item);
    }

    // @Override
    // public void onHiddenChanged(boolean hidden) {
    // super.onHiddenChanged(hidden);
    // this.hidden = hidden;
    // if (!hidden) {
    // refresh();
    // }
    // }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
        ContactListJson contactListJson = new ContactListJson(
                Config.getUserName(),
                Config.getUserToken());
        getContactListFromServer(Constants.FRIENDSLIST, contactListJson);
    }

    /**
     * 删除联系人
     * 
     * @param tobeDeleteUser
     */
    public void deleteContact(final FriendsUser tobeDeleteUser) {
        String st1 = getResources().getString(R.string.deleting);
        final String st2 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog pd = new ProgressDialog(mContext);
        pd.setMessage(st1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().contactManager()
                            .deleteContact(tobeDeleteUser.getUsername());
                    // 删除db和内存中此用户的数据
                    UserDao dao = new UserDao(mContext);
                    dao.deleteContact(tobeDeleteUser.getUsername());
                    ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                            .getContactList()
                            .remove(tobeDeleteUser.getUsername());
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            adapter.remove(tobeDeleteUser);
                            adapter.notifyDataSetChanged();

                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(mContext, st2 + e.getMessage(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });

                }

            }
        }).start();

    }

    /**
     * 把user移入到黑名单
     */
    private void moveToBlacklist(final String username) {
        final ProgressDialog pd = new ProgressDialog(mContext);
        String st1 = getResources().getString(R.string.Is_moved_into_blacklist);
        final String st2 = getResources()
                .getString(R.string.Move_into_blacklist_success);
        final String st3 = getResources()
                .getString(R.string.Move_into_blacklist_failure);
        pd.setMessage(st1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 加入到黑名单
                    EMClient.getInstance().contactManager().addUserToBlackList(username,
                            false);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(mContext, st2, Toast.LENGTH_SHORT).show();
                            refresh();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(mContext, st3, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();

    }

    // 刷新ui
    public void refresh() {
        try {
            // 可能会在子线程中调到这方法
            runOnUiThread(new Runnable() {
                public void run() {
                    getContactList();
                    adapter.notifyDataSetChanged();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        if (contactSyncListener != null) {
            HXSDKHelper.getInstance()
                    .removeSyncContactListener(contactSyncListener);
            contactSyncListener = null;
        }

        if (blackListSyncListener != null) {
            HXSDKHelper.getInstance()
                    .removeSyncBlackListListener(blackListSyncListener);
        }

        if (contactInfoSyncListener != null) {
            ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                    .getUserProfileManager()
                    .removeSyncContactInfoListener(contactInfoSyncListener);
        }
        super.onDestroy();
    }

    public void showProgressBar(boolean show) {
        if (progressBar != null) {
            if (show) {
                progressBar.setVisibility(View.VISIBLE);
            } else {
                progressBar.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 获取联系人列表，并过滤掉黑名单和排序
     */
    private void getContactList() {
        contactList.clear();
        // 获取本地好友列表
        Map<String, FriendsUser> users = ((DemoHXSDKHelper) HXSDKHelper
                .getInstance()).getContactList();
        Iterator<Entry<String, FriendsUser>> iterator = users.entrySet()
                .iterator();
        while (iterator.hasNext()) {
            Entry<String, FriendsUser> entry = iterator.next();
            if (!entry.getKey().equals(Constants.NEW_FRIENDS_USERNAME)
                    && !entry.getKey().equals(Constants.GROUP_USERNAME)
                    && !entry.getKey().equals(Constants.CHAT_ROOM)
                    && !blackList.contains(entry.getKey()))
                contactList.add(entry.getValue());
        }
        // 排序
        Collections.sort(contactList, new Comparator<FriendsUser>() {

            @Override
            public int compare(FriendsUser lhs, FriendsUser rhs) {
                return lhs.getHeader().compareTo(rhs.getHeader());
            }
        });

        // 加入"群聊"和"聊天室"
        if (users.get(Constants.GROUP_USERNAME) != null)
            contactList.add(0, users.get(Constants.GROUP_USERNAME));

        // 把"申请与通知"添加到首位
        if (users.get(Constants.NEW_FRIENDS_USERNAME) != null)
            contactList.add(0, users.get(Constants.NEW_FRIENDS_USERNAME));

    }

    void hideSoftKeyboard() {
        if (getWindow()
                .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(
                        getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void init() {
        // setContactListener监听联系人的变化等
        EMClient.getInstance().contactManager()
                .setContactListener(new MyContactListener());

        // 注册一个监听连接状态的listener
        // connectionListener = new MyConnectionListener();
        // EMChatManager.getInstance().addConnectionListener(connectionListener);

        // groupChangeListener = new MyGroupChangeListener();
        // // 注册群聊相关的listener
        // EMGroupManager.getInstance()
        // .addGroupChangeListener(groupChangeListener);
    }

    static void asyncFetchGroupsFromServer() {
        HXSDKHelper.getInstance().asyncFetchGroupsFromServer(new EMCallBack() {

            @Override
            public void onSuccess() {
                HXSDKHelper.getInstance().noitifyGroupSyncListeners(true);

                if (HXSDKHelper.getInstance().isContactsSyncedWithServer()) {
                    HXSDKHelper.getInstance().notifyForRecevingEvents();
                }
            }

            @Override
            public void onError(int code, String message) {
                HXSDKHelper.getInstance().noitifyGroupSyncListeners(false);
            }

            @Override
            public void onProgress(int progress, String status) {

            }

        });
    }

    static void asyncFetchBlackListFromServer() {
        HXSDKHelper.getInstance().asyncFetchBlackListFromServer(
                new EMValueCallBack<List<String>>() {

                    @Override
                    public void onSuccess(List<String> value) {
                        try {
                            EMClient.getInstance().contactManager().saveBlackList(value);
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                        HXSDKHelper.getInstance()
                                .notifyBlackListSyncListener(true);
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        HXSDKHelper.getInstance()
                                .notifyBlackListSyncListener(false);
                    }

                });
    }

    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     * 
     * @param username
     * @param user
     */
    private static void setUserHearder(String username, FriendsUser user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(
                    HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        Log.i(TAG, "headerName:" + headerName + "Header:" + user.getHeader());
    }

    /***
     * 好友变化listener
     * 
     */
    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
            // 保存增加的联系人
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
            Map<String, FriendsUser> toAddUsers = new HashMap<String, FriendsUser>();
                FriendsUser user = setUserHead(username);
                // 添加好友时可能会回调added方法两次
                if (!localUsers.containsKey(username)) {
                    userDao.saveContact(user);
                }
            toAddUsers.put(username, user);
            localUsers.putAll(toAddUsers);
            // 刷新ui
            // if (currentTabIndex == 1)
            refresh();

        }

        @Override
        public void onContactDeleted(final String username) {
            // 被删除
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
                localUsers.remove(username);
                userDao.deleteContact(username);
                inviteMessgeDao.deleteMessage(username);
            runOnUiThread(new Runnable() {
                public void run() {
                    // 如果正在与此用户的聊天页面
                    String st10 = getResources()
                            .getString(R.string.have_you_removed);
                    if (ChatActivity.activityInstance != null && username
                            .contains(ChatActivity.activityInstance
                                    .getToChatUsername())) {
                        Toast.makeText(mContext, ChatActivity.activityInstance
                                .getToChatUsername() + st10, Toast.LENGTH_SHORT).show();
                        ChatActivity.activityInstance.finish();
                    }
                    // updateUnreadLabel();
                    // 刷新ui
                    refresh();
                    // chatHistoryFragment.refresh();
                }
            });

        }

        @Override
        public void onContactInvited(String username, String reason) {

            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null
                        && inviteMessage.getFrom().equals(username)) {
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onFriendRequestAccepted(String username) {
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onFriendRequestDeclined(String username) {

            // 参考同意，被邀请实现此功能,demo未实现
            Log.d(username, username + "拒绝了你的好友请求");
        }

    }

    /** 显示通知栏点击跳转到指定Activity */
    public void showIntentActivityNotify(String message, int from) {
        mBuilder = new NotificationCompat.Builder(this);
        String mes = getString(R.string.new_message);
        // //在通知栏上点击此通知后自动清除此通知
        if (from == 0) {
            mes = getString(R.string.request_add_friend);
        } else if (from == 1) {
            mes = getString(R.string.agree_request_add_friend);
        } else if (from == 2) {
            mes = getString(R.string.request_group_chat);
        }
        mBuilder.setAutoCancel(true)
                // 点击后让通知将消失
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(message + mes).setTicker(message + mes)
                .setSmallIcon(R.drawable.lfy);
        // 点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, NewFriendsMsgActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(101, mBuilder.build());
    }

    /**
     * MyGroupChangeListener
     */
    public class MyGroupChangeListener implements EMGroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName,
                                         String inviter, String reason) {

            boolean hasGroup = false;
            for (EMGroup group : EMClient.getInstance().groupManager().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3));
            // 保存邀请消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            runOnUiThread(new Runnable() {
                public void run() {
                    // updateUnreadLabel();
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccepted(String groupId, String inviter,
                                        String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee,
                                         String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {

            // 提示用户被T了，demo省略此步骤
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        if (CommonUtils.getTopActivity(mContext)
                                .equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        EMLog.e(TAG, "refresh exception " + e.getMessage());
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(String groupId, String groupName) {

            // 群被解散
            // 提示用户群被解散,demo省略
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String groupId, String groupName,
                                                    String inviter) {
            boolean hasGroup = false;
            for (EMGroup group : EMClient.getInstance().groupManager().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3));
            // 保存邀请消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            runOnUiThread(new Runnable() {
                public void run() {
                    // updateUnreadLabel();
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onRequestToJoinReceived(String groupId, String groupName,
                                          String applyer, String reason) {

            // 用户申请加入群聊
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入群聊：" + groupName);
            msg.setStatus(InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onRequestToJoinAccepted(String groupId, String groupName,
                                        String accepter) {

            String st4 = getResources()
                    .getString(R.string.Agreed_to_your_group_chat_application);
            // 加群申请被同意
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMCmdMessageBody(accepter + " " + st4));
            // 保存同意消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            runOnUiThread(new Runnable() {
                public void run() {
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    // chatAllHistoryActivity.refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onRequestToJoinDeclined(String groupId, String groupName,
                                          String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }
    }

    /**
     * 获取未读申请与通知消息
     * 
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList()
                .get(Constants.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList()
                            .get(Constants.NEW_FRIENDS_USERNAME)
                            .getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * set head
     * 
     * @param username
     * @return
     */
    FriendsUser setUserHead(String username) {
        FriendsUser user = new FriendsUser(username);
      //  user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(
                    HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        Log.i(TAG, "username" + username + "head" + user.getHeader());
        return user;
    }

    /**
     * 保存提示新消息
     * 
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // 提示有新消息
        HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null);

        refresh();
    }

    /**
     * 保存邀请等msg
     * 
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        // 未读数加1
        FriendsUser user = ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                .getContactList().get(Constants.NEW_FRIENDS_USERNAME);
        if (user.getUnreadMsgCount() == 0)
            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }

    /**
     * 获取好友列表
     * 
     * @param getContactListUrl
     * @param mContactListJson
     */
    public void getContactListFromServer(String getContactListUrl,
            ContactListJson mContactListJson) {
        Log.i(TAG, "<loginRequest>--<onResponse>--上传的JSon数据：  LoginJson = "
                + mContactListJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult<List<Friends>>>() {
        }.getType();
        JsonListRequest<BaseResult<List<Friends>>> request = new JsonListRequest<BaseResult<List<Friends>>>(
                mContext, Method.POST, getContactListUrl,
                mContactListJson.toString(), null, null, type, true,
                new Listener<BaseResult<List<Friends>>>() {

                    @Override
                    public void onResponse(BaseResult<List<Friends>> arg0) {
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        List<Friends> data = null;
                        Friends friends = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = arg0.getData();
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            // 登陆成功，保存用户名密码
                            if (null != data) {
                                Context context = HXSDKHelper.getInstance()
                                        .getAppContext();
                                Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
                                // 添加user"申请与通知"
                                FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
                               // newFriends.setUsername(
                                //        Constant.NEW_FRIENDS_USERNAME);
                                String strChat = context.getString(
                                        R.string.Application_and_notify);
                                newFriends.setNickname(strChat);
                                userlist.put(Constants.NEW_FRIENDS_USERNAME,
                                        newFriends);
                                // 添加"群聊"
                                FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
                                String strGroup = context
                                        .getString(R.string.group_chat);
                              //  groupUser.setUsername(Constant.GROUP_USERNAME);
                                groupUser.setNickname(strGroup);
                                groupUser.setHeader("");
                                userlist.put(Constants.GROUP_USERNAME,
                                        groupUser);
                                for (int i = 0; i < data.size(); i++) {

                                    String nick = data.get(i).getFname();
                                    String avatar = Constants.GETIMAGE
                                            + data.get(i).getFimage();
                                    String username = data.get(i)
                                            .getFusername();
                                    FriendsUser friendsUser = new FriendsUser(username);
                                  //  friendsUser.setUsername(username);
                                    friendsUser.setNickname(nick);
                                    friendsUser.setAvatar(avatar);
                                    setUserHearder(username, friendsUser);
                                    userlist.put(username, friendsUser);
                                    if (nick != null && !nick.equals("")) {
                                        Log.i("nick", nick);
                                    }
                                }
                                // 存入内存
                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                        .setContactList(userlist);
                                // 存入db
                                UserDao dao = new UserDao(mContext);
                                List<FriendsUser> users = new ArrayList<FriendsUser>(
                                        userlist.values());
                                dao.saveContactList(users);
                            } else {
                                Toast.makeText(mContext, "获取联系人失败！",
                                        Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        adapter.notifyDataSetChanged();
                        mPullListView.onPullDownRefreshComplete();
                        mPullListView.onPullUpRefreshComplete();
                        mPullListView.setHasMoreData(hasMoreData);
                        mPullListView.setHasData(hasData);
                        isPullDownRefreshing = false;
                        isPullUpRefreshing = false;
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
                            Toast.makeText(mContext,
                                    getString(
                                            R.string.service_temporarily_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                        if (isPullDownRefreshing || isPullUpRefreshing) {
                            mPullListView.onPullDownRefreshComplete();
                            mPullListView.onPullUpRefreshComplete();
                            isPullDownRefreshing = false;
                            isPullUpRefreshing = false;
                        }
                    }

                });
        VolleyUtil.addRequest(request);
    }

}
